#!/usr/bin/python3

import sys
import requests
import os


def get_rebuilds_list(package_name: str) -> list:
    response = requests.get(
        "https://aosc-packages.cth451.me/revdep/{}?type=json".format(package_name))
    response.raise_for_status()
    package_info = response.json()
    rebuilds_list = []
    rebuilds_list = [package for group in package_info["sobreaks"]
                     for package in group if package not in rebuilds_list]
    if package_info["sobreaks_circular"] != None:
        rebuilds_list += package_info["sobreaks_circular"]
    if len(rebuilds_list) == 0:
        print("Package {} has nothing to rebuild!".format(package_name))
        exit(0)

    # remove +32 packages
    rebuilds_list = [i for i in rebuilds_list if not i.endswith("+32")]

    # remove transitional packages/latx
    transitional_pkgs = ["gst-plugins-good-1-0", "latx"]
    rebuilds_list = [i for i in rebuilds_list if i not in transitional_pkgs]

    print("Packages to rebuild:", ", ".join(rebuilds_list))
    return rebuilds_list


def gen_rebuilds_list_string(rebuilds_list: list) -> str:
    rebuilds_path_list = [search_package_path(i) for i in rebuilds_list]
    rebuilds_path_list = [
        i for i in rebuilds_path_list if i != None and len(i.split('/')) == 2]
    return "\n".join(sorted(rebuilds_path_list)) + "\n"


def search_package_path(package_name: str) -> str:
    with os.scandir(".") as dir1:
        for section in dir1:
            if section.is_dir() and not section.name.startswith('.'):
                with os.scandir(section) as dir2:
                    for package in dir2:
                        if package.is_dir() and os.path.isdir(os.path.join(package, "autobuild")):
                            if package.name == package_name:
                                return package.path[2:]
                            else:
                                continue

                        # search subpackage, like arch-install-scripts/01-genfstab
                        path = package
                        if os.path.isdir(path) and section.name != "groups":
                            with os.scandir(path) as dir3:
                                for subpackage in dir3:
                                    if subpackage.name != "autobuild" and subpackage.is_dir():
                                        try:
                                            with open(os.path.join(subpackage, "defines"), "r") as f:
                                                defines = f.readlines()
                                        except:
                                            with open(os.path.join(subpackage, "autobuild/defines"), "r") as f:
                                                defines = f.readlines()
                                        finally:
                                            for line in defines:
                                                if "PKGNAME=" in line and ("{}\n".format(package_name) == line[8:] or "\"{}\"\n".format(package_name) == line[8:]):
                                                    return package.path[2:]


def write_string_to_file(package_name: str, rebuilds_path_list_str: str) -> None:
    with open('groups/{}-rebuilds'.format(package_name), "w") as f:
        f.write(rebuilds_path_list_str)
        print('groups/{}-rebuilds created!'.format(package_name))


def main():
    if len(sys.argv) != 2:
        print("Usage: make-rebuilds-list PACKAGE_NAME")
        exit(1)
    package_name = sys.argv[1]
    request_list = get_rebuilds_list(package_name)
    rebuilds_path_list_str = gen_rebuilds_list_string(request_list)
    write_string_to_file(package_name, rebuilds_path_list_str)


if __name__ == '__main__':
    main()
